package com.yhgm.utils;

import com.yhgm.constant.Constant;
import com.yhgm.model.dto.FilesDto;
import com.yhgm.model.rep.ServerFileInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;

/**
 * @author xinmiao
 * @description
 * @date 2023/3/11 11:00
 */
@Component
@Slf4j
public class FileUtils {
    public R getDirs(String parentDir) {
        Map<String, Object> data = new HashMap<>();
        System.out.println(Constant.proBiologyImagePath + parentDir);
        File file = new File(Constant.proBiologyImagePath + parentDir);
        if (!file.exists()) {
            return R.error("文件夹不存在");
        }
        data.put("dirs", file.list());
        return R.ok(data, "getDirs");
    }

    public R getAll(String parentDir) {
        Map<String, Object> data = new HashMap<>();
        File file = new File(Constant.proBiologyImagePath + parentDir);
        //System.out.println(file.getAbsolutePath());
        if (!file.exists()) {
            return R.error("文件夹不存在");
        }
        String[] fs = file.list();
        if (fs == null || fs.length == 0) {
            data.put("list", new ArrayList<>());
            return R.ok(data, "getAll");
        }
        List<String> files = new ArrayList<>(fs.length);
        Collections.addAll(files, fs);
        FilesDto filesDto = new FilesDto();
        filesDto.setDirs(new ArrayList<>());
        filesDto.setFiles(new ArrayList<>());
        for (String s : files) {
            if (s.indexOf('.') == -1) {
                filesDto.getDirs().add(s);
            } else {
                ServerFileInfo server = new ServerFileInfo();
                server.setFilename(s);
                server.setUrl(Constant.FILE_URL_PREFIX + parentDir + s);
                server.setFileSize(new File(Constant.proBiologyImagePath + parentDir + s).length());
                filesDto.getFiles().add(server);
            }
        }
        data.put("dirs", filesDto.getDirs());
        data.put("files", filesDto.getFiles());
        return R.ok(data, "getAll");
    }

    public R mkdir(String currentDir, String newDir) {
        File file = new File(Constant.proBiologyImagePath + currentDir);
        if (!file.exists()) {
            return R.error("不存在的当前文件夹");
        }
        File newFile = new File(Constant.proBiologyImagePath + currentDir + newDir);
        if (newFile.exists()) {
            return R.error("已存在该文件夹");
        } else {
            newFile.mkdir();
        }
        return R.ok("新建文件夹成功");
    }

    public R deleteDir(String targetDir) {
        File newFile = new File(Constant.proBiologyImagePath + targetDir);
        if (newFile.exists()) {
            try {
                Files.delete(newFile.toPath());
            } catch (IOException e) {
                e.printStackTrace();
                return R.error("只能删除空文件夹");
            }
        } else {
            return R.error("目标文件夹不存在");
        }
        return R.ok("删除目标文件夹成功");
    }

    public Boolean transToMp4(String src) {
        try {
            // 输入文件路径
            //String inputFile = src;
            // 输出文件路径
            String outputFile = src.substring(0, src.lastIndexOf(".") + 1) + Constant.VIDEO_TYPE;
            // 创建FFmpeg命令
            List<String> command = new ArrayList<>();
            command.add(Constant.FFMPEG_PATH_1);
            //command.add("-version");
            //command.add("ffmpeg");
//            command.add("-i");
//            command.add(src);
//            command.add("-c:v");
//            command.add("libx264");
//            //command.add("copy");
//            command.add("-c:a");
//            //command.add("copy");
//            command.add("libx264");
//            command.add(outputFile);
            command.add("-i");
            command.add(src);
            command.add("-y");
            command.add("-q:v");
            command.add("1");
            command.add(outputFile);
            // 执行命令
//            for (int i=0;i<command.size();i++){
//                System.out.print(command.get(i)+" ");
//            }
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
            //Process process = builder.start();
//            BufferedReader reader = new BufferedReader(
//                    new InputStreamReader(process.getInputStream()));
//            String line;
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line);
//            }
            //process.waitFor();
            //System.out.println("视频转换成功！");
            return true;
            //} catch (IOException | InterruptedException e) {
        } catch (IOException e) {
            //System.out.println("视频转换出错：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public void out(File file,HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }
}

